package com.liqi.web.controller.openapi.middleware;

import com.liqi.monitor.domain.dto.*;
import com.liqi.statistics.service.DvServiceTimeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.liqi.common.core.domain.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.liqi.common.core.controller.BaseController;
import com.liqi.common.core.domain.AjaxResult;
import com.liqi.common.utils.StringUtils;
import com.liqi.deployment.domain.DvDeployment;
import com.liqi.deployment.service.IDvDeploymentService;
import com.liqi.monitor.domain.DvDeploymentDiskInfo;
import com.liqi.monitor.domain.DvDeploymentSystem;
import com.liqi.monitor.domain.DvHeartbeat;
import com.liqi.monitor.domain.dto.HeartBeatDto;
import com.liqi.monitor.service.IDvDeploymentDiskInfoService;
import com.liqi.monitor.service.IDvDeploymentSystemService;
import com.liqi.monitor.service.IDvFaultLogService;
import com.liqi.monitor.service.IDvHeartbeatService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.List;

/**
 * 中间件心跳上报接口
 * 
 * @author xxx
 */
@Api(tags = "提供给中间件的接口")
@RestController
@RequestMapping("/openApi/middleware")
public class HeartBeatController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(HeartBeatController.class);
	@Autowired
	private IDvDeploymentSystemService dvDeploymentSystemService;

	@Autowired
	private IDvFaultLogService dvFaultLogService;

	@Autowired
	private IDvHeartbeatService dvHeartBeatService;
	@Autowired
	private DvServiceTimeService dvServiceTimeService;
	@Autowired
	private IDvDeploymentDiskInfoService  diskInfoService;
	@Autowired
	private IDvDeploymentService dvDeploymentService;
	/**
	 * 心跳上报
	 */
	@ApiOperation("心跳上报")
	@PostMapping(value = "/saveHeartbeat")
	public R heartbeat(@Validated @RequestBody HeartBeatDto heartBeatDto) {
		String deviceId = heartBeatDto.getDeviceId();
		if (StringUtils.isBlank(deviceId)) {
			return R.fail("自编设备编号不能为空。" + deviceId);
		}
		DvDeployment dvDeployment = dvDeploymentService.getByDeviceId(deviceId);
		if (null == dvDeployment) {
			return R.fail("找不到该设备。"+ deviceId);
		}
		// 业务逻辑
		// 写入设备心跳数据表
		// 根据device_id查询dv_heartbeat表是否存在device_id
		DvHeartbeat dvHeartbeat = dvHeartBeatService.selectDvHeartbeatByDeviceId(deviceId);
		if (dvHeartbeat == null) {
			DvHeartbeat dvh = new DvHeartbeat();
			dvh.setDeviceId(deviceId);
			dvHeartBeatService.insertDvHeartbeat(dvh);
		} else {
			dvHeartBeatService.updateDvHeartbeat(dvHeartbeat);			
		}

		// ============写入设备运行表
		DvSystemInfoDto system = heartBeatDto.getSystemInfo();
		if (system != null) {
			// 检测自检信息是否超阀值
			DvDeploymentSystem temp = dvDeploymentSystemService.selectDeploymentByDeviceId(deviceId);

			boolean insertFlag = false;
			if (temp == null) {
				insertFlag = true;
				temp = new DvDeploymentSystem();
			}
			temp.setDeviceId(deviceId);
			temp.setOsVersion(system.getOsVersion());
			temp.setOtherMessage(system.getOtherMessage());
			temp.setMiddlewareVersion(system.getMiddlewareVersion());

			MemoryDto memory = system.getMemory();
			if (memory != null) {
				temp.setMemory(memory.getTotal());
				if (StringUtils.isNotBlank(memory.getUsageRate())&&!memory.getUsageRate().equals("-1")) {
					temp.setMemoryRate(memory.getUsageRate());
				}
			}

			DiskDto disk = system.getDisk();
			if (disk != null) {
				temp.setDisk(disk.getTotalCapacity());
				if (StringUtils.isNotBlank(disk.getTotalUsageRate())&&!disk.getTotalUsageRate().equals("-1")) {
					temp.setDiskRate(disk.getTotalUsageRate());
				}
			}

			CpuDto cpu = system.getCpu();
			if (cpu != null) {
				temp.setCpu(cpu.getProduct());
				if (StringUtils.isNotBlank(cpu.getUsageRate())&&!cpu.getUsageRate().equals("-1")) {
					temp.setCpuRate(cpu.getUsageRate());
				}
			}

			NetworkAdapter networkAdapter = system.getNetworkAdapter();
			if (networkAdapter != null) {
				temp.setIpAddress(networkAdapter.getIp());
				temp.setMac(networkAdapter.getMac());
			}

			PrinterDto printer = system.getPrinter();
			if (printer != null) {
				if (StringUtils.isNotBlank(printer.getPaperRate())&&!printer.getPaperRate().equals("-1")) {
					temp.setPaperRate(printer.getPaperRate());
				}
				if (StringUtils.isNotBlank(printer.getCcolor())&&!printer.getCcolor().equals("-1")) {
					temp.setCColor(printer.getCcolor());
				}
				if (StringUtils.isNotBlank(printer.getKcolor())&&!printer.getKcolor().equals("-1")) {
					temp.setKColor(printer.getKcolor());
				}
				if (StringUtils.isNotBlank(printer.getMcolor())&&!printer.getMcolor().equals("-1")) {
					temp.setMColor(printer.getMcolor());
				}
				if (StringUtils.isNotBlank(printer.getYcolor())&&!printer.getYcolor().equals("-1")) {
					temp.setYColor(printer.getYcolor());
				}
			}

			if (insertFlag) {
				dvDeploymentSystemService.insertDvDeploymentSystem(temp);
			} else {
				dvDeploymentSystemService.updateDeploymentSystemByDeviceId(temp);
			}
			//写入磁盘分区使用信息表
			if(disk != null && disk.getPartitions() != null && disk.getPartitions().size() > 0) {
				List<DiskPartitions> partitions = disk.getPartitions();
				for(DiskPartitions  ps: partitions) {
					DvDeploymentDiskInfo diskInfo = new DvDeploymentDiskInfo();
					diskInfo.setDeviceId(deviceId);		
					diskInfo.setName(ps.getName());
					List<DvDeploymentDiskInfo> diskInfoList = diskInfoService.selectDvDeploymentDiskInfoList(diskInfo);
					//这些条件不能放查询里面，作为条件。
					diskInfo.setCapacity(ps.getCapacity());
					if (!ps.getUsageRate().equals("-1")) {
						diskInfo.setRate(ps.getUsageRate());
					}					
					if (diskInfoList != null && diskInfoList.size() > 0) {
						diskInfo.setId(diskInfoList.get(0).getId());
						diskInfoService.updateDvDeploymentDiskInfo(diskInfo);
					}else {
						diskInfoService.insertDvDeploymentDiskInfo(diskInfo);
					}
				}
			}

			// 内存使用率，硬盘使用率，纸张墨盒使用率达到阈值，生成一条异常信息
			dvFaultLogService.insertThresholdFaultLog(temp);
		}
			dvServiceTimeService.setTime(deviceId);

			R r = R.ok();
			return r;
	}


}
